package com.ycsj.goldmedalnewconcept.teacher.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnBindViewListener;
import com.timmy.tdialog.listener.OnViewClickListener;
import com.ycsj.common.base.BaseLazyFragment;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.TDialogManager;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.common.view.flowlayout.FlowLayout;
import com.ycsj.common.view.flowlayout.TagAdapter;
import com.ycsj.common.view.flowlayout.TagFlowLayout;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.TkKeys;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.teacher.bean.AnswerInfo;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * 阅读理解 填空题的子Fragment
 * Created by Administrator on 2018/12/11 0011.
 */

public class ItemReadFillingFragment extends BaseLazyFragment {

    //题目内容
    @BindView(R.id.tv_question)
    TextView tvQuestion;
    //作答的线性布局
    @BindView(R.id.ll_user_zd)
    LinearLayout ll_user_zd;
    //作答的流式布局
    @BindView(R.id.fl_own_layout)
    TagFlowLayout flOwnLayout;
    //正确答案的流式布局
    @BindView(R.id.fl_right_answer_layout)
    TagFlowLayout flRightAnswerLayout;
    //全校正确率的整体布局
    @BindView(R.id.ll_qxzql)
    LinearLayout llQxzql;
    //全校正确率的TextView
    @BindView(R.id.tv_qxzql)
    TextView tvQxzql;

    //解析
    @BindView(R.id.tv_parse_answer)
    TextView tvParseAnswer;
    //完成状态需要显示的布局
    @BindView(R.id.ll_show_answer)
    LinearLayout llShowAnswer;


    //页面的数据模型
    private AnswerInfo answerInfo;

    //当前题目在大题的位置
    private int currPos;

    //当前题目的的正确答案
    private String rihgtAnswer;

    //学生做题0  1学生查看解析 2老师查看题和解析-有人做(全校正确率和小题正确率都显示) 3(习题分析)老师查看题和解析-没人做,对应查看单题
    private int state;

    //切割题目的正则表达式
    public static final String reg = "__{1,}";

    //默认的用于替换用户输入答案的值
    public static final String DEFAULTCONTENT = "_____";

    //用于保存用户输入的内容,初始值为服务器返回的_____5个下划线
    private Map<Integer, String> inputContent;

    //使用正则表达式切割题干后的字符串集合
    private String[] sentences;

    //正确答案的组(a;b)或者(b;a)
    private String[] answerGroups;

    //序号标记
    private String[] letters = {"①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨", "⑩"};


    public static final ItemReadFillingFragment newInstance(AnswerInfo info, int questionNum, int state) {
        ItemReadFillingFragment itemReadFillingFragment = new ItemReadFillingFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", info);
        bundle.putInt("curr", questionNum);
        bundle.putInt("state", state);
        itemReadFillingFragment.setArguments(bundle);
        return itemReadFillingFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fargment_item_read_filling;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

    }

    @Override
    protected void init(View view, Bundle savedInstanceState) {
        super.init(view, savedInstanceState);

        //获取页面数据
        initIntent();

        //初始化视图状态
        initView();
    }

    /**
     * 获取页面数据
     */
    private void initIntent() {
        answerInfo = (AnswerInfo) getArguments().getSerializable("data");
        //正确答案
        if (null != answerInfo) {
            rihgtAnswer = answerInfo.rightAnswer;
            currPos = getArguments().getInt("curr");
            state = getArguments().getInt("state");
        }
    }


    /**
     * 初始化视图状态
     */
    public void initView() {
        if (state == 0) {
            //学生未做题
            llShowAnswer.setVisibility(View.GONE);

            //未完成状态下设置页面数据,包含处理题目的显示以及点击事件的处理等
            initNoCompleteData();

        } else if (state == 1) {
            //学生查看解析

            //作答布局显示
            ll_user_zd.setVisibility(View.VISIBLE);

            //全校正确率和小题正确率不显示
            llQxzql.setVisibility(View.GONE);
            llShowAnswer.setVisibility(View.VISIBLE);

            initHasCompletedData();

            initBottomData();

        } else if (state == 2) {
            //老师查看学生解析(有人做)

            //作答布局显示
            ll_user_zd.setVisibility(View.GONE);

            //全校正确率和小题正确率显示
            llQxzql.setVisibility(View.VISIBLE);
            llShowAnswer.setVisibility(View.VISIBLE);

            initNoCompleteData();
            tvQuestion.setEnabled(false);

            initBottomData();

        } else if (state == 3) {
            //查看单题或老师查看学生(没人做)

            //作答布局不显示
            ll_user_zd.setVisibility(View.GONE);

            //全校正确率和小题正确率显示
            llQxzql.setVisibility(View.GONE);
            llShowAnswer.setVisibility(View.VISIBLE);

            initNoCompleteData();
            tvQuestion.setEnabled(false);
            initBottomData();
        }

    }

    /**
     * 未完成状态下处理数据
     */
    private void initNoCompleteData() {

        //获取题目内容
        if (null != answerInfo) {
            String questionContent = answerInfo.qustionContent;

            //第一步:设置题目内容
            tvQuestion.setText(questionContent);

            //第二步:处理正确答案,这里的正确答案包含多个空的情况,空与空之间的答案用;分割,  每个空的而正确答案以/分割
            String rightAnswer = answerInfo.rightAnswer;
            // a;b / b;a
            if (!TextUtils.isEmpty(rightAnswer)) {

                //已"/"切割获取答案的组
                answerGroups = rightAnswer.split("/");

                //取答案数组的第0个元素使用;切割获取题目中空格的数量
                String[] rightAnswerArrays = answerGroups[0].split(";");

                //初始化用户填入的答案的数据,长度应该跟空格的数量一致
                //初始化创建Map用以保存输入的内容,默认值是DEFAULTCONTENT
                inputContent = new LinkedHashMap<>();

                for (int i = 0; i < rightAnswerArrays.length; i++) {
                    inputContent.put(i, DEFAULTCONTENT);
                }

                //第四步:处理题目内容中空格的点击事件
                //将服务器返回的题干使用正则表达式切割
                sentences = questionContent.split(reg);
                sycStudentQuestionState();
            }
        }
    }

    /**
     * 已完成状态下处理数据
     */
    private void initHasCompletedData() {

        if (answerInfo == null) {
            return;
        }

        //已完成状态下取用户的作答答案
        String ownAnswers = answerInfo.chooseAnswer;

        if (!TextUtils.isEmpty(ownAnswers)) {
            //每道题可能有多空,使用∩切割获取该小题中用户填入的答案

            String[] ownAnswerArrays = ownAnswers.split("∩");

            //初始化内容
            inputContent = new LinkedHashMap<>();

            for (int i = 0; i < ownAnswerArrays.length; i++) {
                inputContent.put(i, ownAnswerArrays[i]);
            }

            //题干内容,服务器返回
            String questionContent = answerInfo.qustionContent;

            //将服务器返回的题干使用正则表达式切割
            sentences = questionContent.split(reg);

            //创建序号的集合
            String[] indexNums = new String[inputContent.size()];

            for (int i = 0; i < inputContent.size(); i++) {
                //这里控制是否显示每空的序号
                indexNums[i] = letters[i];
            }

            //拼接需要重新显示的字符串
            String content = "";
            if (sentences.length == inputContent.size()) {
                //题干内容以__结尾,切割的数组长度和填空的位置一样
                for (int i = 0; i < sentences.length; i++) {
                    content += sentences[i] + indexNums[i] + inputContent.get(i);
                }

            } else {
                //题干内容不以__结尾,切割的字符串数组长度比需要填空的位置多一个
                for (int i = 0; i <= sentences.length - 2; i++) {
                    //sentences的是8,但是inputContent的长度是7
                    content += sentences[i] + indexNums[i] + inputContent.get(i);
                }
                content += sentences[sentences.length - 1];
            }

            //计算文字变色和添加下划线
            SpannableStringBuilder stringBuilder = new SpannableStringBuilder(content);

            for (int i = 0; i < indexNums.length; i++) {

                //序号需要变色的起始位置
                int start = 0;
                int end = 0;

                for (int j = 0; j <= i; j++) {
                    start += sentences[j].length();
                }

                for (int k = 0; k <= i - 1; k++) {
                    start += indexNums[k].length();
                    start += inputContent.get(k).length();
                }

                end = start + indexNums[i].length();

                //设置变色
                stringBuilder.setSpan(new ForegroundColorSpan(Color.parseColor("#EC8628")), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                //需要添加下划线的起始位置
                int clickStart = 0;
                int clikcEnd = 0;

                for (int j = 0; j <= i; j++) {
                    clickStart += sentences[j].length();
                    clickStart += indexNums[j].length();
                }

                for (int k = 0; k <= i - 1; k++) {
                    clickStart += inputContent.get(k).length();
                }

                clikcEnd = clickStart + inputContent.get(i).length();

                //设置下划线和点击变色的文字位置
                stringBuilder.setSpan(new TextClick() {
                    @Override
                    public void onClick(View view) {
                    }
                }, clickStart, clikcEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            }

            //设置文字
            tvQuestion.setText(stringBuilder);
        }

    }

    /**
     * 同步学生将进入时题干的方法
     */
    private void sycStudentQuestionState() {

        //创建序号的集合
        String[] indexNums = new String[inputContent.size()];

        for (int i = 0; i < inputContent.size(); i++) {
            //这里控制是否显示每空的序号
            indexNums[i] = letters[i];
        }

        //拼接需要重新显示的字符串
        String content = "";
        if (sentences.length == inputContent.size()) {
            //题干内容以__结尾,切割的数组长度和填空的位置一样
            for (int i = 0; i < sentences.length; i++) {
                content += sentences[i] + indexNums[i] + inputContent.get(i);
            }
        } else {
            //题干内容不以__结尾,切割的字符串数组长度比需要填空的位置多一个
            for (int i = 0; i <= sentences.length - 2; i++) {
                //sentences的是8,但是inputContent的长度是7
                content += sentences[i] + indexNums[i] + inputContent.get(i);
            }
            content += sentences[sentences.length - 1];
        }

        //计算文字变色和添加下划线
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(content);

        for (int i = 0; i < indexNums.length; i++) {

            //记录点击的文字位置
            final int index = i;

            //序号需要变色的起始位置
            int start = 0;
            int end = 0;

            for (int j = 0; j <= i; j++) {
                start += sentences[j].length();
            }

            for (int k = 0; k <= i - 1; k++) {
                start += indexNums[k].length();
                start += inputContent.get(k).length();
            }

            end = start + indexNums[i].length();

            //设置变色
            stringBuilder.setSpan(new ForegroundColorSpan(Color.parseColor("#EC8628")), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);


            //需要添加下划线的起始位置
            int clickStart = 0;
            int clikcEnd = 0;

            for (int j = 0; j <= i; j++) {
                clickStart += sentences[j].length();
                clickStart += indexNums[j].length();
            }

            for (int k = 0; k <= i - 1; k++) {
                clickStart += inputContent.get(k).length();
            }

            clikcEnd = clickStart + inputContent.get(i).length();

            //设置下划线和点击变色的文字位置

            stringBuilder.setSpan(new TextClick() {
                @Override
                public void onClick(View view) {
                    if (state == 0) {
                        //只有在学生未作答时才点击弹框
                        if("0".equals(AccountUtils.getRole(getActivity()))){
                            //学生可以点击
                            showInputPop(index);
                        }else{
                            //家长不可点击

                        }

                    }
                }
            }, clickStart, clikcEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        }

        //设置文字
        tvQuestion.setText(stringBuilder);

        //设置该方法后,点击事件才能生效
        tvQuestion.setMovementMethod(LinkMovementMethod.getInstance());
    }


    /**
     * 点击空格位置弹出输入框的方法
     *
     * @param index
     */
    private void showInputPop(final int index) {

        TDialogManager.show(getActivity(), getActivity().getSupportFragmentManager(), R.layout.teacher_app_pop_input_form_blank, 0.3f, new OnBindViewListener() {
            @Override
            public void bindView(BindViewHolder viewHolder) {
                viewHolder.setText(R.id.tv_pop_content, "请输入答案");
            }
        }, new OnViewClickListener() {
            @Override
            public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                switch (view.getId()) {
                    case R.id.tv_cancel:
                        TDialogManager.dismiss();
                        break;
                    case R.id.tv_ok:
                        EditText etInput = viewHolder.getView(R.id.et_input);
                        //第一步:获取输入框的文字,进行非空判断
                        String content = etInput.getText().toString().trim();
                        if (TextUtils.isEmpty(content)) {
                            //没有输入单词
                            UiUtils.Toast("您还没有输入单词", false);
                            return;
                        } else {
                            //已经输入了单词
                            //第二步:将输入的单词回显到点击的空格位置

                            //将用于保存输入框的内容的集合中点击的位置的值进行同步
                            inputContent.put(index, "  " + content + "  ");

                            //再次设置点击事件
                            sycStudentQuestionState();

                            //通过EventBs将用户作答本小题的相关信息传递给TkMainActivity保存
                            //currPos对应的每个大题的小题的位置
                            int choosePos = currPos;

                            //对于阅读填空题型,由于每个小题中可能存在多个空格的问题
                            //所以在回传信息时,需要保证每个小题都做完的前提下在进行回传
                            //回传时需要将题目中的所有空格的填写的答案用∩拼接
                            //同时判断正确率的时需要判断每个空是否都正确在回传该小题的正确率

                            //判断该题是否做完的方法
                            if (hasDownOver(inputContent)) {

                                //获取该小题用户输入的答案
                                String chooseAnswer = getAllInputAnswers(inputContent);

                                //获取该小题是否回答正确
                                boolean chooseResult = getCorrect(inputContent, answerGroups);

                                BusInfo busInfo = new BusInfo();
                                busInfo.tkMsg = TkKeys.TKMsg;
                                busInfo.tkChoosePos = choosePos;
                                busInfo.tkChooseAnswer = chooseAnswer;
                                busInfo.tkChooseResult = chooseResult;
                                EventBus.getDefault().post(busInfo);

                            }


                            //关闭对话框
                            TDialogManager.dismiss();
                        }

                        break;
                }
            }
        }, R.id.tv_cancel, R.id.tv_ok);
    }


    /**
     * 获取该小题是否回答正确的方法
     * 计算规则:必须每个小题都正确该小题才正确
     *
     * @param inputContent
     * @return
     */
    private boolean getCorrect(Map<Integer, String> inputContent, String[] answerGroups) {
        boolean res = false;

        //获取输入的每个空的答案的拼接字符串,拼接规则,答案与答案之间用"; "来连接
        List<String> inputAnswers = new ArrayList<>();
        for (String value : inputContent.values()) {
            inputAnswers.add(value);
        }

        //用户输入的所有空拼接的答案组
        String inputAnswerGroup = "";
        for (int i = 0; i < inputAnswers.size(); i++) {
            if (i == 0) {
                //第一个
                inputAnswerGroup += inputAnswers.get(i).trim();
            } else {
                //其它,使用￠+当前自己的作答进行连接
                inputAnswerGroup += "; " + inputAnswers.get(i).trim();
            }
        }

        for (int i = 0; i < answerGroups.length; i++) {
            Log.i("test", "正确答案" + answerGroups[i]);
            if (inputAnswerGroup.equals(answerGroups[i].trim())) {
                res = true;
                break;
            }
        }

        return res;
    }

    /**
     * 获取该小题的所有空的拼接答案的方法
     *
     * @param inputContent
     * @return
     */
    private String getAllInputAnswers(Map<Integer, String> inputContent) {
        String res = "";
        List<String> answers = new ArrayList<>();
        for (String value : inputContent.values()) {
            answers.add(value.trim());
        }

        if (answers.size() == 1) {
            //只有一空
            res = answers.get(0);
        } else {
            //有多空
            for (int i = 0; i < answers.size(); i++) {
                if (i == 0) {
                    //第一个
                    res += answers.get(i);
                } else {
                    //其它,使用￠+当前自己的作答进行连接
                    res += "∩" + answers.get(i);
                }
            }
        }

        return res;
    }

    /**
     * 判断该题是否做完的方法
     *
     * @param inputContent
     */
    private boolean hasDownOver(Map<Integer, String> inputContent) {

        boolean res = true;

        List<String> answers = new ArrayList<>();
        for (String value : inputContent.values()) {
            answers.add(value);
        }

        for (int i = 0; i < answers.size(); i++) {
            if (answers.get(i).equals(DEFAULTCONTENT)) {
                res = false;
                break;
            }
        }
        return res;
    }

    /**
     * 判断用户输出的答案是否是正确答案的方法
     *
     * @param inputConent
     * @param rightAnswers 每个空的正确答案,该题型一个空可以有多个正确答案,每个答案以/连接
     * @return
     */
    private boolean isAnswerRight(String inputConent, String rightAnswers) {
        boolean res = false;
        if (TextUtils.isEmpty(inputConent) || TextUtils.isEmpty(rightAnswers)) {
            return res;
        } else {
            String[] rightAnswerArryays = rightAnswers.split("/");
            for (int i = 0; i < rightAnswerArryays.length; i++) {
                if (inputConent.equals(rightAnswerArryays[i])) {
                    res = true;
                    break;
                }
            }
            return res;
        }
    }

    /**
     * 点击事件
     */
    private abstract class TextClick extends ClickableSpan {
        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setUnderlineText(true);
            ds.setStrokeWidth(3);
            ds.setColor(Color.parseColor("#EC8628"));
        }

    }

    /**
     * 非做题状态下设置底部作答,正确答案,以及解析的方法
     */
    private void initBottomData() {
        //获取布局管理器
        final LayoutInflater mInflater = LayoutInflater.from(getActivity());

        if (state == 1) {
            //学生查看解析

            //设置作答的流式布局数据
            List<String> ownAnswers = new ArrayList<>();
            //1.获取用户该小题的所有作答的拼接字符串
            String ownAnswer = answerInfo.chooseAnswer;
            if (TextUtils.isEmpty(ownAnswer)) {
                return;
            }
            String[] ownAnswerArrays = ownAnswer.split("∩");
            for (int i = 0; i < ownAnswerArrays.length; i++) {
                if (!TextUtils.isEmpty(ownAnswerArrays[i])) {
                    ownAnswers.add((i + 1) + "." + ownAnswerArrays[i]);
                } else {
                    ownAnswers.add((i + 1) + "." + "未作答");
                }
            }

            flOwnLayout.setAdapter(new TagAdapter<String>(ownAnswers) {
                @Override
                public View getView(FlowLayout parent, int position, String s) {
                    TextView tv = (TextView) mInflater.inflate(R.layout.teacher_class_tv_ownanswer,
                            flOwnLayout, false);
                    tv.setText(s);
                    return tv;
                }
            });

        }

        //设置正确答案的流式布局
        //正确答案的流式布局的数据
        List<String> rightAnswers = new ArrayList<>();
        //获取所有空的正确答案拼接字符串
        String rightAnswer = answerInfo.rightAnswer;
        if (TextUtils.isEmpty(rightAnswer)) {
            return;
        }

        //正确答案,这里只需要以/切割获取每个空的正确答案字符串即可
        String[] rightAnswerArraysOne = rightAnswer.split("/");

        //多组答案
        if (rightAnswerArraysOne.length > 1) {

            String[] right = new String[rightAnswerArraysOne[0].split(";").length];

            for (int i = 0; i < right.length; i++) {

                for (int j = 0; j < rightAnswerArraysOne.length; j++) {

                    String[] rightTwo = rightAnswerArraysOne[j].split(";");
                    if (j == 0) {
                        right[i] = rightTwo[i];
                    } else {
                        right[i] += "/" + rightTwo[i];
                    }
                }
            }


            for (int i = 0; i < right.length; i++) {
                if (!TextUtils.isEmpty(right[i])) {
                    rightAnswers.add((i + 1) + "." + right[i]);
                }
            }

            flRightAnswerLayout.setAdapter(new TagAdapter<String>(rightAnswers) {
                @Override
                public View getView(FlowLayout parent, int position, String s) {
                    TextView tv = (TextView) mInflater.inflate(R.layout.teacher_class_tv_rightanswer,
                            flRightAnswerLayout, false);
                    tv.setText(s);
                    return tv;
                }
            });
        } else {
            //一组答案
            String[] rightAnswerArrays = rightAnswer.split(";");
            for (int i = 0; i < rightAnswerArrays.length; i++) {
                if (!TextUtils.isEmpty(rightAnswerArrays[i])) {
                    rightAnswers.add((i + 1) + "." + rightAnswerArrays[i]);
                }
            }

            flRightAnswerLayout.setAdapter(new TagAdapter<String>(rightAnswers) {
                @Override
                public View getView(FlowLayout parent, int position, String s) {
                    TextView tv = (TextView) mInflater.inflate(R.layout.teacher_class_tv_rightanswer,
                            flRightAnswerLayout, false);
                    tv.setText(s);
                    return tv;
                }
            });
        }

        if (state == 2) {
            //全校正确率
            tvQxzql.setText(answerInfo.proba);
        }
        //设置解析
        tvParseAnswer.setText(answerInfo.explain.trim().toString());

    }
}
